package com.nxj.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.nxj.io.Resources;
import com.nxj.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    public Configuration parseConfig(InputStream inputStream) throws Exception {
        Document document = new SAXReader().read(inputStream);
        Element rootEle = document.getRootElement();

        List<Element> propertyList = rootEle.selectNodes("//property");
        Properties properties = new Properties();
        for (Element e : propertyList)
            properties.put(e.attributeValue("name"), String.valueOf(e.attributeValue("value")));

        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(String.valueOf(properties.get("driverClass")));
        comboPooledDataSource.setJdbcUrl(String.valueOf(properties.get("jdbcUrl")));
        comboPooledDataSource.setUser(String.valueOf(properties.get("username")));
        comboPooledDataSource.setPassword(String.valueOf(properties.get("password")));

        // 解析 xml 文件设置链接数据源
        configuration.setDataSource(comboPooledDataSource);

        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
        // 解析对应的 datasource 形成对应的 mapper 对象
        List<Element> mapperList = rootEle.selectNodes("//mapper");
        for (Element element : mapperList)
            xmlMapperBuilder.parseMapper(Resources.getResourceAsStream(element.attributeValue("resource")));

        return configuration;
    }

}
